package jwlee.testproxy.javaproxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;

/**
 * java代理机制实现日志输出
 * 
 * InvocationHandler.invoke方法将在被代理类的方法被调用之前触发
 */
public class TimeBookJavaProxy {

	private Logger logger = Logger.getLogger(this.getClass().getName());

	// 绑定委托对象并返回一个代理类
	public Object bind(final Object delegate) {

		InvocationHandler h = new InvocationHandler() {
			@Override
			public Object invoke(Object proxy, Method method, Object[] args)
					throws Throwable {
				// 在方法调用前后进行日志输出
				logger.log(Level.INFO, "----LogProxy.invoke begin... ");
				String argStr = args == null ? "[]" : Arrays.asList(args).toString();
				logger.log(Level.INFO, delegate.getClass().getName() + "."
						+ method.getName() + "(" + argStr.substring(1, argStr.length() - 1) + ")");

				Object result = method.invoke(delegate, args);//

				logger.log(Level.INFO, "----LogProxy.invoke end!");

				return result;
			}
		};

		return Proxy.newProxyInstance(delegate.getClass().getClassLoader(),
				delegate.getClass().getInterfaces(), h);//要绑定接口(这是一个缺陷，cglib弥补了这一缺陷) 
	}
	
	//
	public static void main(String[] args) {
		// 实现了对日志类的重用
		TimeBookJavaProxy logProxy = new TimeBookJavaProxy();
		TimeBookInterface timeBookProxy = (TimeBookInterface) logProxy.bind(new TimeBook());
		timeBookProxy.doAuditing("mzj", 29);
		timeBookProxy.doAuditing();
	}

}
